package com.asset.salesforce.validator;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import com.asset.salesforce.form.AppointmentForm;

public class AppointmentFellowUpDateCheckerConstraintValidator implements ConstraintValidator<AppointmentFellowUpDateChecker,Object> {

        @Override
        public void initialize(AppointmentFellowUpDateChecker arg0) {
                // TODO Auto-generated method stub
               
        }
        
        private boolean isDateNull(String date){
        	if(date!=null&&!date.equalsIgnoreCase("")){
        		return true;
        	}
        	else{
        		return false;
        	}
        }

        @Override
        public boolean isValid(Object arg0, ConstraintValidatorContext constraintValidatorContext) {
                boolean success = false;
                AppointmentForm appointmentForm = (AppointmentForm)arg0;
                String enteredDate = appointmentForm.getDate();
                String fellowDate = appointmentForm.getNextFollowUpDate();
                boolean isDateNull=isDateNull(enteredDate);
                boolean isFollowUpDateNull=isDateNull(fellowDate);
                if(isDateNull==true&&isFollowUpDateNull==true){
                	DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
             		Date date;
             		Date followUpDate;
             		try {
     					date = formatter.parse(enteredDate);
     	    			followUpDate = formatter.parse(fellowDate);
     	                if(fellowDate!=null&&!fellowDate.equalsIgnoreCase("")){
     	                         if(!(enteredDate.equals(""))){
     	                        	 if(date.compareTo(followUpDate)>0){
     	                        		 success = false;
     	                        	 }
     	                        	 else if(date.compareTo(followUpDate)<0){
     	                        		 success = true;
     	                 			}
     	                 			else{
     	                 				success = true;
     	                 			}
     	                         }
     	                 else{success=true;}
     	                 }else{success=true;}
     				} catch (ParseException e) {
     					e.printStackTrace();
     				}
                }
                else{
                	success = true;
                }
                 return success;
        }
}

